import { Link, useNavigate } from 'react-router-dom'
import { Card, Breadcrumb, Input, message, Modal, Tooltip, Col, Row, Form, Button, Radio, DatePicker, Select, Popconfirm } from 'antd'
//时间组件汉化
import locale from 'antd/es/date-picker/locale/zh_CN'
import './index.scss'
import { Table, Tag, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import React, { useEffect, useRef, useState } from 'react'
import { AdminUserregister, GetAdmuserinfo, EditAdminUser } from '@/apis/adminuser'
import useAdminUserList from '@/hooks/useAdminUserList'
import { setToken as _setToken } from "@/utils"
import { format } from "date-fns"
import { useDispatch, useSelector } from 'react-redux'
import { number } from 'echarts'
import { clearUserInfo } from '@/store/modules/user'

const { RangePicker } = DatePicker

const UserList = () => {
    //添加修改信息
    const { currentId, authentication, count, reqData, userInfoList, onPageChange, onConfirm, onFinish, getList } = useAdminUserList()
    //定义枚举状态 
    // const administrator_status = {
    //     true: <Tag color="green">管理员</Tag>,
    //     false: <Tag color="default">普通用户</Tag>
    // }
    //表单重置
    const [form] = Form.useForm()
    //表单重置
    const [form2] = Form.useForm()
    //修改数据
    const [loading, setLoading] = useState(false)
    const [open, setOpen] = useState(false)
    //数据状态
    const [userState, setUserState] = useState(false)

    const cardRef = useRef(null); // 获取 Card 的 DOM 元素
    const rowRef = useRef(null); // 获取 Row 的 DOM 元素
    const [tableheight, setTableHeight] = useState(0); // 存储 Row 高度
    const { mobile, is_superuser, id: userid } = useSelector(state => state.user.userInfo)
    const dispatch = useDispatch()
    const navigate = useNavigate()
    // console.log(is_superuser)
    // 获取卡片高度
    useEffect(() => {
        if (is_superuser == "0") {
            if (cardRef.current) {
                const Cardheight = cardRef.current.clientHeight; // 获取卡片高度
                const height = Math.floor(Cardheight - 210)
                setTableHeight(height)
            }
            return
        }
        if (cardRef.current && rowRef.current) {
            const Cardheight = cardRef.current.clientHeight; // 获取卡片高度
            const Rowheight = rowRef.current.clientHeight; // 获取 Row 高度
            const height = Math.floor(Cardheight - Rowheight - 210)
            setTableHeight(height)
        }
    }, []);

    //显示弹窗
    const showModal = async (id) => {
        //添加时候鉴定用户是否有权限
        // if (authentication.code != 200) {
        //     message.error(authentication.message)
        //     return
        // }
        if (is_superuser == "0") {
            message.error("您没有权限")
            return
        }
        setOpen(true)
        form2.setFieldsValue({ id: '', usernames: '', mobiles: '', is_superuser: '', passwords: '', total_token: "", key: "" })
        if (id == "") {
            setUserState(false)
        }
        else {
            setUserState(true)
            // console.log(id)
            const res = await GetAdmuserinfo(id)
            // console.log(res)
            form2.setFieldsValue({
                // id: res.data.id,
                // usernames: res.data.username,
                // phones: res.data.phone,
                // // administrator: res.data.administrator == false ? 0 : 1,
                // accounts: res.data.account,
                id: res.data.id,
                usernames: res.data.username,
                mobiles: res.data.mobile,
                is_superuser: res.data.is_superuser == true ? "1" : "0",
                passwords: res.data.password,
                total_token: res.data.total_token,
                key: res.data.key
            })
        }
    };
    //关闭弹窗
    const handleCancel = () => {
        setOpen(false)
    }

    //提交数据
    const handleOk = async () => {
        setLoading(true)
        try {
            const formdata = await form2.validateFields()
            // console.log(formdata)
            const { id, usernames, mobiles, is_superuser, passwords, total_token, key } = formdata
            // console.log(id)
            const data = {
                "id": id == null || id == "" ? 0 : Number(id),
                "password": passwords,
                "is_superuser": is_superuser == "1" ? true : false,
                "username": usernames,
                "mobile": mobiles,
                "key": key,
                "total_token": total_token
            }
            var res = ""
            if (id == "") {
                //添加
                res = await AdminUserregister(data)
            }
            else {
                //修改
                res = await EditAdminUser(data)
            }

            if (res.code == 200) {
                setOpen(false)
                getList()
                if (userState == true) {
                    if (id == userid) {
                        //同步方法
                        dispatch(clearUserInfo())
                        navigate("/login")
                    }
                    message.success('修改成功')
                }
                else {
                    message.success('添加成功')
                }
            }
            else {
                if (res.status == 403)
                    message.error("您没有权限")
                else
                    message.error(res.message)
            }
        } catch (error) {
            message.error('请填写完整的表单！')
        }
        setLoading(false)
    }

    // 准备列数据
    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
            width: 30,
            hidden: true
        },
        // {
        //     title: '用户名',
        //     dataIndex: 'username',
        //     // width: 180,
        //     // render: cover => {
        //     //     return <img src={cover.images[0] || img404} width={80} height={60} alt="" />
        //     // }
        // },
        {
            title: '用户名',
            // dataIndex: 'account',
            render: data => {
                if (data.id == userid) {
                    return <Tag color="green">{data.username}</Tag>
                }
                else {
                    return data.username
                }
            }
        },
        {
            title: 'key',
            dataIndex: 'key',
            width: 220,
            ellipsis: {
                showTitle: false,
            },
            render: (key) => (
                <Tooltip styles=
                    {{
                        root: {
                            maxWidth: '600px', // 设置最大宽度
                            whiteSpace: 'normal', // 允许换行
                        }
                    }}
                    placement="topLeft" title={key}>
                    {key}
                </Tooltip>
            )
        },
        {
            title: '手机号',
            dataIndex: 'mobile',
            // width: 200
        },
        {
            title: '用户类别',
            dataIndex: 'superuserName',
        },
        {
            title: '总Token',
            dataIndex: 'total_token',
        },
        {
            title: '已使用Token',
            dataIndex: 'tokenUsage',
        },
        {
            title: '使用率',
            dataIndex: 'tokenusagerate',
        },
        // {
        //     title: '用户类别',
        //     dataIndex: 'administrator',
        //     render: data => {
        //         return administrator_status[data]
        //     }
        // },
        // {
        //     title: '创建时间',
        //     dataIndex: 'ceate_time',
        //     render: (ceate_time) => {
        //         if (ceate_time) {
        //             return format(new Date(ceate_time), "yyyy-MM-dd HH:mm:ss")
        //         }
        //     }
        // },
        // {
        //     title: '最后登陆时间',
        //     dataIndex: 'last_login',
        //     render: (update_time) => {
        //         if (update_time) {
        //             return format(new Date(update_time), "yyyy-MM-dd HH:mm:ss")
        //         }
        //     }
        // },
    ]

    if (is_superuser != "0") {
        columns.push({
            title: '操作',
            render: data => {
                return (
                    <Space size="middle">

                        <Button type="primary" shape="circle" onClick={() => showModal(`${data.id}`)} icon={<EditOutlined />} />

                        <Popconfirm
                            title="删除用户"
                            description="确定要删除当前用户吗?"
                            onConfirm={() => { onConfirm(data.id) }}
                            // onCancel={cancel}
                            okText="是"
                            cancelText="否"
                            key={2}
                        >
                            <Button
                                type="primary"
                                danger
                                shape="circle"
                                icon={<DeleteOutlined />}
                            />
                        </Popconfirm>
                    </Space>
                )
            }
        })
    }

    return (
        <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
            {/* <Card
                title={
                    <Breadcrumb items={[
                        { title: <Link to={'/'}>首页</Link> },
                        { title: '管理员列表' },
                    ]} />
                }
                style={{ marginBottom: 10 }}
            >
                <Form initialValues={{}} form={form} onFinish={val => onFinish(val)}>
                    <Row gutter={24}>
                        <Col span={7} key={1}>
                            <Form.Item label="用户类别" name="administrator">
                                <Radio.Group>
                                    <Radio value={''}>全部</Radio>
                                    <Radio value={1}>管理员</Radio>
                                    <Radio value={0}>普通用户</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>
                        <Col span={6} key={3}>
                            <Form.Item label="用户名" name="username">
                                <Input placeholder="" />
                            </Form.Item>
                        </Col>
                        <Col span={6} key={6}>
                            <Form.Item label="手机号" name="mobile">
                                <Input placeholder="" />
                            </Form.Item>
                        </Col>
                        <Col span={10} key={7}>
                            <Form.Item>
                                <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
                                    筛选
                                </Button>
                                <Button style={{ marginLeft: "20px" }} htmlType="Reset" >
                                    重置
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Card> */}
            <div style={{ height: "100%", overflow: "hidden" }}>
                {/* 表格数据 */}
                <Card title={`根据筛选条件共查询到 ${count} 条结果：`} style={{ tableLayout: "fixed", height: "100%" }} ref={cardRef}>
                    {is_superuser != "0" && <Row justify="start" className='RowPadd' ref={rowRef}>
                        <Col >
                            <Button onClick={() => showModal("")} type="primary">添加</Button>
                        </Col>
                    </Row>}
                    <Modal
                        open={open}
                        title={userState ? "修改用户" : "'添加用户"}
                        onOk={handleOk}
                        onCancel={handleCancel}
                        width={600}
                        centered={true}
                        footer={[
                            <Button type="primary" key="submit" loading={loading} onClick={handleOk}>
                                {userState ? "修改" : "添加"}
                            </Button>,
                            <Button
                                type="primary"
                                key="close"
                                onClick={handleCancel}
                            >
                                关闭
                            </Button>,
                        ]}
                    >
                        <div style={{ padding: "40px", paddingBottom: "5px" }}>
                            <Form form={form2} initialValues={{}} >
                                {/* 传入locale属性 控制中文显示*/}
                                <Form.Item label="id" name="id" hidden={true} >
                                    <Input placeholder="" />
                                </Form.Item>
                                <Form.Item label="用户名" name="usernames" rules={[
                                    {
                                        required: true,
                                        message: '请输入用户名',
                                    },
                                ]}>
                                    <Input placeholder="请输入用户名" disabled={userState} />
                                </Form.Item>
                                <Form.Item label="手机" name="mobiles">
                                    <Input placeholder="请输入手机号" />
                                </Form.Item>
                                <Form.Item label="key" name="key" rules={[
                                    {
                                        required: true,
                                        message: '请输入手机',
                                    },
                                ]}>
                                    <Input placeholder="请输入key" />
                                </Form.Item>
                                <Form.Item label="管理员" name="is_superuser" rules={[
                                    {
                                        required: true,
                                        message: '请输入管理员',
                                    },
                                ]} >
                                    <Radio.Group>
                                        <Radio value="1">是</Radio>
                                        <Radio value="0">否</Radio>
                                    </Radio.Group>
                                </Form.Item>
                                <Form.Item label="token" name="total_token" rules={[
                                    {
                                        required: true,
                                        message: '请输入token',
                                    },
                                ]}>
                                    <Input placeholder="请输入账户" />
                                </Form.Item >
                                {/* {
                                    !userState && <Form.Item label="密码" name="passwords" rules={[
                                        {
                                            required: true,
                                            message: '请输入密码',
                                        },
                                    ]}>
                                        <Input.Password size="large" placeholder="请输入密码" />
                                    </Form.Item>
                                } */}
                                <Form.Item label="密码" name="passwords" rules={[
                                    {
                                        required: true,
                                        message: '请输入密码',
                                    },
                                ]}>
                                    <Input.Password size="large" placeholder="请输入密码" />
                                </Form.Item>
                            </Form>
                        </div>
                    </Modal>
                    <Table rowKey="id" columns={columns} dataSource={userInfoList} scroll={{ y: tableheight }}
                        pagination={{
                            total: count,
                            pageSize: reqData.MaxResultCount,
                            onChange: onPageChange
                        }}
                    />
                </Card>
            </div>
        </div>
    )
}

export default UserList